package amit.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import amit.browser.Browser;

/**
 * Holding all the general method to handle GUI common cases. e.g. Insert List
 * of values into text field.
 * 
 * @author ido
 * 
 */
@SuppressWarnings({"StringConcatenationInsideStringBufferAppend"})
public class GuiUtil {

	public static final int SIZE_OF_LINE = 80;
	
	public static Color darkRedColor  = new Color(102, 0, 0);
	public static Color darkGreenColor = new Color(0, 102, 0);
	public static Color gainsBoroColor = new Color(220, 220, 220);
	public static Color lavenderColor = new Color(230, 230, 250);
	
	/** Format to use to display the date property. */
	public static final DateFormat DATE_FORMAT = new SimpleDateFormat(
			"MM-dd-yyyy");
	
	public static final DateFormat DATE_AND_TIME_FORMAT = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss z");

	/**
	 * The sharedInstance init
	 */
  public static GuiUtil sharedInstance = new GuiUtil();
  /**
	 * private Ctor.
	 */
	private GuiUtil() {
		super();
//		Toolkit tk = Toolkit.getDefaultToolkit();
//		setDefaultBrowser();
	}

	/**
	 * On Windows make sure jdic will use IE

	private void setDefaultBrowser() {
		String osStr = System.getProperty("os.name").toLowerCase();
		if (osStr.indexOf("windows") > -1) {
			BrowserEngineManager engineManager = BrowserEngineManager.instance();
			engineManager.setActiveEngine(BrowserEngineManager.IE);
			System.out.println("Runing on Windows so setting the browser to IE");
		}
	}		*/ 
 
	/**
	 * Centre a Window, Frame, JFrame, Dialog
	 * After packing a Frame or Dialog, centre it on the screen.
	 */
	public static void centre(Window w) {
		Dimension us = w.getSize(), them = Toolkit.getDefaultToolkit()
				.getScreenSize();
		int newX = (them.width - us.width) / 2;
		int newY = (them.height - us.height) / 2;
		w.setLocation(newX, newY);
	}

	/**
	 * 
	 * @param location
	 * @return
	 */
	public ImageIcon loadIcon(String location) {
		URL iconUrl;
		ImageIcon icon;
		try {
			iconUrl = getClass().getResource(location);
			icon = new ImageIcon(iconUrl);
			return icon;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param location
	 * @return
	 */
	public Image loadImage(String location) {
		URL imageUrl;
		Image icon;
		try {
			imageUrl = getClass().getResource(location);
			icon = Toolkit.getDefaultToolkit().getImage(imageUrl);
			return icon;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * Replace the HTML tags '<' and '>' from strHTML
	 * @param strHTML
	 * @return
	 */
	public String replaceHtmlTags(String strHTML) {		  
		strHTML =  strHTML.replace("<", "&lt;");
		strHTML = strHTML.replace(">", "&gt;");
		return strHTML;
		  
	}
	
	/**
	 * multi line tooltip
	 * @param str
	 * @return
	 */
	public String breakToLines(String str) {
		StringBuffer returnStr = new StringBuffer("<html>");
		int index = 0; 
		while (index + SIZE_OF_LINE < str.length()) {
			String tmpStr = GuiUtil.sharedInstance.replaceHtmlTags(str.substring(index, index+SIZE_OF_LINE));
			returnStr.append("<p>" + tmpStr + "</p>");
			index += SIZE_OF_LINE+1;
		}
		
		returnStr.append("<p>" + GuiUtil.sharedInstance.replaceHtmlTags(
				str.substring(index, str.length())) + "</p></html>");
		return returnStr.toString();
	
	}
	
	/**
	 * load the current url from the row that is selected
	 * 
	 * @param urlStr
	 */
	public void showUrl(final Browser browser, final String urlStr) {
		try {
			if (urlStr.length() > 1) {
				browser.loadUrl(urlStr);
			} else {
				System.out.println("This is the url to load: " + urlStr);
			}
		} catch (Exception e) {
			System.out.println("Could not show url: " + urlStr + " ex:" +
					stackToString(e));
		}
	}
	
	
	public String stackToString(Exception e) {
		if (e != null) {
			try {
			    StringWriter sw = new StringWriter();
			    PrintWriter pw = new PrintWriter(sw);
			    e.printStackTrace(pw);
			    return sw.toString() + "\n";
		    }
			catch(Exception ex) {
				return "Could not show the stackTrace in String\n"+ex.getMessage();
			}
		}
		return "exception=null";
	}
	
	/**
	 * No result panel - will be used in cases where the result/review panels need it
	 * @return
	 */
	public JPanel getNoResultPanel(String text) {
		JPanel noResultPanel = new JPanel();
		noResultPanel.setLayout(new BoxLayout(noResultPanel, BoxLayout.Y_AXIS));
		noResultPanel.add(new JLabel(text));
		noResultPanel.setBorder(BorderFactory.createTitledBorder(""));
		noResultPanel.setPreferredSize(new Dimension(300, 300));
		return noResultPanel;

	}

	/**
	 * 
	 * @return
	 */
	public JPanel getWaitingPanel(String waitingText) {
		JPanel waitPanel = new JPanel(new BorderLayout()); 

		waitPanel.setBackground(Color.WHITE);
		JLabel waitingLabel = new JLabel(waitingText, 
				GuiUtil.sharedInstance.loadIcon("/wait_fifa.gif"), JLabel.CENTER);
		waitPanel.add(waitingLabel);
		waitPanel.setBorder(BorderFactory.createTitledBorder(""));
		return waitPanel;
	}
	
	/**
	 * 
	 * @param list
	 * @param delimiter
   * @return
	 */
	public static String getListAsString(List<String> list, String delimiter) {
		if (list == null) {
			return "";
		}
		
		StringBuilder sb = new StringBuilder();
    for (String element : list) {
      if (sb.length() != 0)
        sb.append(delimiter);
      sb.append(element);
    }
    return sb.toString();
		
	}
	/**
	 * 
	 * @param arr
	 * @return
	 */
	public String displayArray(String[] arr) {
		if (arr == null || arr.length == 0) {
			return "";
		}
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			buf.append(arr[i]);
			if (i < arr.length - 1) {
				buf.append("\n");
			}
		}
		return buf.toString();
	}
	
	public String displayArray(int[] arr) {
		if (arr == null || arr.length == 0) {
			return "";
		}
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			buf.append(arr[i]);
			if (i < arr.length - 1) {
				buf.append(", ");
			}
		}
		return buf.toString();
	}

} // end of GuiUtil